let showLoadingFlag = false;
const logFlag = true; //是否显示日志
const api = require('./api')

//提示框
function myShowToast(e) {
    if (showLoadingFlag == true) {
        myHideLoading();
    }
    wx.showToast({
        title: e,
        icon: 'none',
        duration: 1500
    });
}

//提示框
function myShowToast2(e) {
    if (showLoadingFlag == true) {
        myHideLoading();
    }
    wx.showToast({
        title: e,
        icon: 'none',
        duration: 10000
    });
}

//显示Loading
function myShowLoading(e) {
    showLoadingFlag = true;
    wx.showLoading({
        title: e,
        mask: true,
    })
}

//隐藏Loading
function myHideLoading(e) {
    wx.hideLoading({
        success: (res) => {},
    })
}

//弹框
function myShowModal(title, message, confirmText) {
    wx.showModal({
        title: title,
        content: message,
        confirmText: confirmText,
        showCancel: false,
        success(res) {
            if (res.confirm) {
                console.log('用户点击确定')
            }
        }
    })
}

//字符串补位
function prefixZero(num, n) {
    return (Array(n).join(0) + num).slice(-n);
}
// 16进制的字符串转2进制
function hexToBinary(hexStr) {
    if (hexStr.length <= 0) {
        return
    } else {
        let binaryStr = ""
        for (let char of hexStr.toLocaleUpperCase()) {
            switch (char) {
                case "0":
                    binaryStr = binaryStr + "0000"
                    break;
                case "1":
                    binaryStr = binaryStr + "0001"
                    break;
                case "2":
                    binaryStr = binaryStr + "0010"
                    break;
                case "3":
                    binaryStr = binaryStr + "0011"
                    break;
                case "4":
                    binaryStr = binaryStr + "0100"
                    break;
                case "5":
                    binaryStr = binaryStr + "0101"
                    break;
                case "6":
                    binaryStr = binaryStr + "0110"
                    break;
                case "7":
                    binaryStr = binaryStr + "0111"
                    break;
                case "8":
                    binaryStr = binaryStr + "1000"
                    break;
                case "9":
                    binaryStr = binaryStr + "1001"
                    break;
                case "A":
                    binaryStr = binaryStr + "1010"
                    break;
                case "B":
                    binaryStr = binaryStr + "1011"
                    break;
                case "C":
                    binaryStr = binaryStr + "1100"
                    break;
                case "D":
                    binaryStr = binaryStr + "1101"
                    break;
                case "E":
                    binaryStr = binaryStr + "1110"
                    break;
                case "F":
                    binaryStr = binaryStr + "1111"
                    break;
            }
        }
        return binaryStr
    }
}

//获取jscode
function getJscode() {
    return new Promise((resolve, reject) => {
        wx.login({
            success(res) {
                let jscode = res.code
                console.log('res', res.code)
                resolve(jscode)
            },
            fail(res) {
                reject(res)
                console.error("微信获取code失败")
            }
        })
    })
}

function scanQRCode(options) {
    const _this = this
    if (JSON.stringify(options) == '{}') {
        return
    } //没有携带参数
    getApp().globalData.scan_device_id = null
    if (options.device_code) {
        getApp().globalData.scan_device_id = options.device_code //小程序水牌
    } else if (options.qrcode) {
        console.log("options.qrcode===>", options.qrcode)
        console.log("token===>", getApp().globalData.token)
        //新版水牌
        api.bedSide({
            qrcode: options.qrcode
        }, getApp().globalData.token).then((res) => {
            console.log("新版水牌===>", res.data.data)
            let result = res.data.data
            if (res.data.data) {
                getApp().globalData.bedInfo = result
            } else {
                _this.myShowToast("智能床二维码异常，请联系酒店前台", 5000)
                return
            }
        })
    }

}
//订阅消息
async function subscribe() {
    const _this = this
    wx.requestSubscribeMessage({
        tmplIds: ['9r4DM3t-6PaF6MWRFJBwvst8wjCKhwR7aByDpxGaRGw', 'yT2ktR0dTazLfnAcg9YZ61QDzI8aAr6pTdyfTbmKpww'],
        success(res) {
            let sum = 0
            for (let key in res) {
                if (res[key] == 'reject') {
                    sum = sum + 1
                }
            }
            console.log('sum', sum)
            if (sum < 2) {
                let nowTime = new Date().getTime()
                let tempTime = new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getDate()
                let standardTime = new Date(tempTime + ' 12:00:00').getTime() //当日12点毫秒数
                let standardTime2 = standardTime + 24 * 60 * 60 * 1000 //次日12点毫秒数
                if (nowTime < standardTime) {
                    wx.setStorageSync('subcribe', standardTime)
                } else {
                    wx.setStorageSync('subcribe', standardTime2)
                }
                // console.log('订阅授权成功', res, getApp().globalData.needsubscribe, standardTime, standardTime2)
            }

        },
        fail(res) {
            console.log('订阅失败', res)
        }
    })

}
//登录
async function login() {
    return new Promise((resolve, reject) => {
        this.myShowLoading('加载中')
        getJscode().then((js_code) => {
            console.log('jscode', js_code)
            api.getOpenId({
                js_code: js_code
            }).then(res => {
                let open_id = res.data.data.open_id
                // let open_id = 'oIZ5W5H50KuAFU99boQKRdHk7zN0'
                getApp().globalData.openid = open_id
                api.checkOpenId({
                    open_id: open_id
                }).then(result => {
                    console.log("是否已注册====>", result.data.data)
                    let is_exist = result.data.data
                    console.log('is_exist', is_exist)
                    if (is_exist == true) {
                        getApp().globalData.nopermission = false
                        api.login({
                            open_id
                        }).then(async function (loginResult) {
                            myHideLoading()
                            console.log("loginResult===>", loginResult.data.data.token)
                            getApp().globalData.token = loginResult.data.data.token ? loginResult.data.data.token : ''
                            getApp().globalData.userId = loginResult.data.data.user_id ? loginResult.data.data.user_id : ''
                            wx.setStorageSync('user_id', getApp().globalData.user_id)
                            wx.setStorageSync('token', getApp().globalData.token)
                            wx.setStorageSync('open_id', open_id)
                            let data = {
                                user_id: getApp().globalData.userId
                            }
                            myShowLoading('用户信息加载中')
                            await api.getBindInfo(data, getApp().globalData.token).then(res => {
                                let hoteldata = res.data.data
                                if (hoteldata.device_id != undefined) {
                                    getApp().globalData.deviceId = hoteldata.device_id
                                    getApp().globalData.failDevice = hoteldata.device_id
                                    getApp().globalData.dataswitch = hoteldata.data_switch
                                    getApp().globalData.needConnect = true
                                    getApp().globalData.bedside = hoteldata.bed_side
                                    getApp().globalData.bedInfo[0] = hoteldata.device_id
                                    getApp().globalData.bedInfo[1] = hoteldata.device_id_second
                                    getApp().globalData.stateInfo[0] = hoteldata.device_id_online_flag
                                    getApp().globalData.stateInfo[1] = hoteldata.device_id_second_online_flag
                                    if (hoteldata.device_id_second != null && hoteldata.device_id_second != undefined) {
                                        getApp().globalData.deviceId2 = hoteldata.device_id_second
                                    }
                                } else {
                                    getApp().globalData.deviceId = null
                                    getApp().globalData.needsubscribe = false
                                }
                                myHideLoading()
                            })
                            await api.getAlarmClockList(getApp().globalData.token).then(res => {
                                if (res.data.code == 200) {
                                    if (res.data.data.length > 0) {
                                        getApp().globalData.hasalarm = true
                                    }
                                }
                            })
                            getApp().globalData.bluetoothInfo = null
                            getApp().globalData.bluetoothInfo2 = null
                            resolve()
                        })
                    } else if (is_exist == false) {
                        getApp().globalData.nopermission = true
                        myHideLoading();
                        resolve()
                    }
                    console.log('per', getApp().globalData.nopermission)
                })
            })
        })
        // }
    })
}
async function insertRemoteKey(device_id, control_key, control_code) {
    let data = {
        device_id: device_id,
        control_key: control_key,
        control_key_code: control_code
    }
    api.insertRemoteKey(data, getApp().globalData.token).then(res => {
        if (res.data.code == 200) {
            console.log('记录按键', device_id, control_key, control_code)
        } else {
            console.log(res.data.msg)
        }
    })
}
//日期格式化
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function getYestoday() {
    return new Date(new Date().getTime() - 1000 * 60 * 60 * 24).Format("yyyy-MM-dd")
}

function getToday() {
    return new Date().Format("yyyy-MM-dd")
}

function getTomorrow() {
    return new Date(new Date().getTime() + 1000 * 60 * 60 * 24).Format("yyyy-MM-dd")
}
module.exports = {
    myShowToast,
    myShowModal,
    myShowLoading,
    myHideLoading,
    prefixZero,
    startBluetoothDevicesDiscovery,
    getBluetoothDevices,
    onBluetoothDeviceFound,
    stopBluetoothDevicesDiscovery,
    createBLEConnection,
    getBLEDeviceServices,
    filterService,
    getDeviceCharacter,
    notifyBLECharacteristicValueChange,
    closeBLEConnection,
    closeBluetoothAdapter,
    hexToBinary,
    scanQRCode,
    login,
    subscribe,
    insertRemoteKey,
    getYestoday,
    getToday,
    getTomorrow
}

let timeoutID;
//搜索设备
function startBluetoothDevicesDiscovery() {
    return new Promise((resolve, reject) => {
        timeoutID = setTimeout(() => {
            stopBluetoothDevicesDiscovery();
            myShowToast2("连接床失败，请您联系工作人员查看床是否正常");
            setTimeout(() => {
                wx.navigateBack({
                    delta: 3 //默认值是1
                })

            }, 3000);
        }, 15000);

        wx.startBluetoothDevicesDiscovery({
            services: [],
            success: function (res) {
                if (logFlag) {
                    console.log("success startBluetoothDevicesDiscovery:", res)
                }
                resolve(res);
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail startBluetoothDevicesDiscovery:", res)
                }
                reject({
                    message: "开始搜索设备失败"
                })
            }
        })
    }).catch((res) => {

    })
}

//获取蓝牙设备
function getBluetoothDevices(bluetoothName) {
    return new Promise((resolve, reject) => {
        wx.getBluetoothDevices({
            success: (res) => {
                let devices = res.devices;
                if (logFlag) {
                    console.log("success getBluetoothDevices:", devices)
                }
                let device_id;
                for (let device of devices) {
                    if (device.name == bluetoothName || device.localName == bluetoothName) {
                        device_id = device.deviceId;
                        console.log("success bluetoothName:", bluetoothName)
                        console.log("success device.name:", device.name)
                        console.log("success localName:", device.localName)
                        console.log("success device_id:", device_id)
                        stopBluetoothDevicesDiscovery();
                        clearTimeout(timeoutID);
                        resolve(device_id);
                    }
                }
                if (!device_id) {
                    resolve();
                }
            },
        })
    }).catch((res) => {

    })
}

//停止蓝牙搜索
function stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
        success: (res) => {
            console.log('关闭蓝牙停止搜索成功');
        },
        fail: (res) => {
            console.log('关闭蓝牙停止搜索失败');
        },
    })
}

//打开蓝牙搜索
function onBluetoothDeviceFound(bluetoothName) {
    return new Promise((resolve, reject) => {
        wx.onBluetoothDeviceFound(function (res) {
            let devices = res.devices;
            if (logFlag) {
                console.log("success onBluetoothDeviceFound:", devices);
            }
            for (let device of devices) {
                if (device.name == bluetoothName || device.localName == bluetoothName) {
                    let device_id = device.deviceId;
                    stopBluetoothDevicesDiscovery();
                    clearTimeout(timeoutID);
                    resolve(device_id);
                }
            }
        });
    }).catch((res) => {
        stopBluetoothDevicesDiscovery();
        clearTimeout(timeoutID);
        myShowToast2("连接床失败，请您联系工作人员查看床是否正常");
    })
}

//创建蓝牙连接
function createBLEConnection(deviceID) {
    console.log('aaaaaaaaaaaaaaaa:', deviceID)
    return new Promise((resolve, reject) => {
        wx.createBLEConnection({
            deviceId: deviceID,
            timeout: 10000,
            success: function (res) {
                if (logFlag) {
                    console.log("success createBLEConnection:", res);
                }
                resolve(res);
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail createBLEConnection:", res);
                }
                resolve();
            }
        })
    })
}

//获取蓝牙服务
function getBLEDeviceServices(deviceID) {
    return new Promise((resolve, reject) => {
        wx.getBLEDeviceServices({
            deviceId: deviceID,
            success: function (res) {
                if (logFlag) {
                    console.log("success getBLEDeviceServices:", res);
                }
                resolve(res)
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail getBLEDeviceServices:", res);
                }
                resolve();
            }
        })
    })
}

//过滤蓝牙设备
function filterService(services) {
    return new Promise((resolve, reject) => {
        let serviceIndex = 0;
        let servicesInfo = {};
        console.log(services)
        for (let service of services) {
            console.log('service' + service)
            if (service.uuid.toUpperCase().indexOf("FFE5") != -1) {
                servicesInfo.writeServiceID = service.uuid;
                serviceIndex++;
            } else if (service.uuid.toUpperCase().indexOf("FFE0") != -1) {
                servicesInfo.readServiceID = service.uuid;
                serviceIndex++;
            } else if (service.uuid.toUpperCase().indexOf("0001") != -1) {
                servicesInfo.writeServiceID = services[0].uuid;
                servicesInfo.readServiceID = services[0].uuid;
                serviceIndex = 2
            } else {
                servicesInfo.writeServiceID = services[0].uuid;
                servicesInfo.readServiceID = services[0].uuid;
                serviceIndex = 2
            }
        }
        if (serviceIndex == 2) {
            if (logFlag) {
                console.log("success filterService:", servicesInfo);
            }
            resolve(servicesInfo);
        } else {
            if (logFlag) {
                console.log("fail filterService:", servicesInfo);
            }
            resolve();
        }

    })
}

//获取蓝牙服务特征值
function getDeviceCharacter(deviceID, serviceID) {
    return new Promise((resolve, reject) => {
        wx.getBLEDeviceCharacteristics({
            deviceId: deviceID,
            serviceId: serviceID,
            success: function (res) {
                if (logFlag) {
                    console.log("success getDeviceCharacter:", res);
                }
                resolve(res);
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail getDeviceCharacter:", res);
                }
                resolve();
            }
        })
    })
}

//监听蓝牙设备特征值变化
function notifyBLECharacteristicValueChange(deviceID, serviceID, characteristicID) {
    return new Promise((resolve, reject) => {
        wx.notifyBLECharacteristicValueChange({
            state: true,
            deviceId: deviceID,
            serviceId: serviceID,
            characteristicId: characteristicID,
            success: function (res) {
                if (logFlag) {
                    console.log("success notifyBLECharacteristicValueChange:", res);
                }
                resolve(res);
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail notifyBLECharacteristicValueChange:", res);
                }
                resolve();
            },
        })
    })
}

//断开蓝牙连接
function closeBLEConnection(deviceID) {
    return new Promise((resolve, reject) => {
        wx.closeBLEConnection({
            deviceId: deviceID,
            success: function (res) {
                if (logFlag) {
                    console.log("success closeBLEConnection:", res);
                }
                closeBluetoothAdapter();
                resolve(res);
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail closeBLEConnection:", res);
                }
                resolve();
            }
        });
    })
}

//关闭蓝牙
function closeBluetoothAdapter() {
    return new Promise((resolve, reject) => {
        wx.closeBluetoothAdapter({
            success: function (res) {
                if (logFlag) {
                    console.log("success closeBluetoothAdapter:", res);
                }
                resolve(res);
            },
            fail: function (res) {
                if (logFlag) {
                    console.log("fail closeBluetoothAdapter:", res);
                }
                resolve();
            },
        })
    })
}